<?php
// +----------------------------------------------------------------------
// | User: DaMing
// +----------------------------------------------------------------------
// | Email: 3228985941@qq.com
// +----------------------------------------------------------------------
// | Date: 2021/12/14
// +----------------------------------------------------------------------

namespace app\adminapi;


use app\dm\exceptions\AdminException;
use app\dm\exceptions\ApiException;
use app\dm\exceptions\AuthException;
use think\exception\DbException;
use think\exception\ValidateException;
use think\exception\Handle;
use think\Log;
use think\Response;
use think\response\Json;
use Throwable;


/**
 * 自定义异常，用于接管系统异常处理
 * Class AdminExceptionHandle
 * @package app\adminapi
 */
class AdminExceptionHandle extends Handle
{
    /**
     * 记录异常信息（包括日志或者其它方式记录）
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 开启调试模式走系统异常
        if (config('app.app_debug')) {
            return parent::render($request, $e);
        }

        // 添加自定义异常处理机制
        if ($e instanceof DbException) {
            $insideCode = $e->getCode() ?: 400;
            $message = $e->getMessage();
        } elseif ($e instanceof AuthException || $e instanceof ValidateException || $e instanceof ApiException) {
            $insideCode = $e->getCode() ?: 400;
            $message = $e->getMessage();
        } elseif ($e instanceof AdminException) {
            $insideCode = $e->getCode() ?: 400;
            $message = $e->getMessage();
        } else {
            $insideCode = '999999';
            $message = $e->getMessage();
        }
        $ret = [
            'code' => $insideCode,
            'msg'  => $message,
        ];
        return json($ret, 200);
    }

}
